//
//  CWQPrepareForVideoVC.m
//  RTMPiOSDemo
//
//  Created by 陈武琦 on 16/8/2.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "CWQPrepareForVideoVC.h"
#import "Masonry.h"
#import "CWQVideoIntroductView.h"
#import "CWQVideoCommentCell.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "WCNMulTextEditVC.h"
#import "CWQInputCommentView.h"
#import "CWQVideoCommentSectionHeader.h"
#import "HELVedioListModel.h"
#import "HELSuperTableView.h"
#import "HELCourseCommentModel.h"
#import "AppDelegate.h"
#import "NSString+Utilities.h"
#import "UITableView+MTTHeaderFooterFittingHeight.h"

static NSString * const cellID = @"cwqVideoCommentCellID";
static NSString * const headerId = @"CWQVideoCommentSectionHeaderID";
@interface CWQPrepareForVideoVC ()<UITableViewDataSource,UITableViewDelegate,CWQInputCommentViewDelegate>{
    CWQVideoIntroductView *_introductView;

}

@property(nonatomic, strong)HELSuperTableView *cwq_tableView;
//上拉加载的页面
@property (nonatomic, assign) CGFloat heightOfIntroduction_displayPartContent;
@property (nonatomic, assign) CGFloat heightOfIntroduction_displayAllContent;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) HELVedioListModel *model;;

@property(nonatomic, strong) NSArray *commentDataArray;

@end

@implementation CWQPrepareForVideoVC

- (instancetype)initWithModel:(HELVedioListModel *)model {
   self = [super init];
    if (self) {
        _model = model;
        self.rtmpUrl = _model.video_url;
        _videoWidgetFrame = CGRectMake(0, 0, kScreenWidth, kScreenWidth*0.5);
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setVideoUI];
    [self setUpViews];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
}

- (void)setVideoUI {
    
    CGFloat origionY = CGRectGetMaxY(_videoWidgetFrame) - 40;
    [_playMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(origionY);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(@40);
    }];
    
}

- (void)setUpViews {
    
    CGFloat origionY = CGRectGetMaxY(_videoWidgetFrame)+5;
   
    
    NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"CWQInputCommentView" owner:nil options:nil];
    CWQInputCommentView *commentInputView= [nibViews lastObject];
    commentInputView.delegate = self;
    [self addSubViewToBack:commentInputView];
    [commentInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(49);
    }];
    
    [self addSubViewToBack:self.cwq_tableView];
    [self.cwq_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(origionY);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(-49);
    }];
    
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"CWQVideoIntroductView" owner:nil options:nil];
    _introductView = [views lastObject];
    _introductView.title.text = self.model.video_name;
    _introductView.content.text = self.model.video_desc;
    weakSelf_define;
    _introductView.clickBlick  = ^(BOOL is_displayAll){
        
        [weakSelf.cwq_tableView mtt_updateTableHeaderViewHeightWithConfig:^(id view) {
            CWQVideoIntroductView *head = view;
            head.title.text = weakSelf.model.video_name;
            head.content.text = weakSelf.model.video_desc;
            if (is_displayAll) {
                head.content.numberOfLines = 0;
            }else {
                head.content.numberOfLines = 1;
            }
        } animated:YES];

    };

    self.cwq_tableView.tableHeaderView = _introductView;
    [self.cwq_tableView mtt_updateTableHeaderViewHeightWithAnimated:NO];
    
    // 添加下拉刷新头部控件
    [self.cwq_tableView wsj_HeaderRefreshBlock:^{
        //请求加载数据
        weakSelf.page = 1;
        [weakSelf requesetCommentData:YES];
    }];
    
    [self.cwq_tableView addLegendFooterWithRefreshingBlock:^{
        weakSelf.page++;
        //请求加载数据
        [weakSelf requesetCommentData:NO];
    }];
    self.page = 1;
    [self requesetCommentData:YES];
}

- (void)addSubViewToBack:(UIView *)view {

    [self.view addSubview:view];
    [self.view sendSubviewToBack:view];

}

- (HELSuperTableView *)cwq_tableView {
    
    if (!_cwq_tableView) {
        _cwq_tableView = [[HELSuperTableView alloc] initWithFrame:CGRectMake(0, 0, 320, 100) style:UITableViewStylePlain];
        [_cwq_tableView registerNib:[UINib nibWithNibName:@"CWQVideoCommentCell" bundle:nil] forCellReuseIdentifier:cellID];
        [_cwq_tableView registerClass:[CWQVideoCommentSectionHeader class] forHeaderFooterViewReuseIdentifier:headerId];
        _cwq_tableView.dataSource = self;
        _cwq_tableView.delegate = self;
        _cwq_tableView.tableFooterView = [UIView new];
//         _cwq_tableView.tableHeaderView = [UIView new];
        _cwq_tableView.showsVerticalScrollIndicator = NO;
    }
    return  _cwq_tableView;
}

//点击评论
- (void)clickInputView:(CWQInputCommentView *)commentView {

        weakSelf_define;
        WCNMulTextEditVC *vc =[[WCNMulTextEditVC  alloc] initWithType:0];
        vc.canEmpty = NO;
        vc.title =@"写评论";
        vc.textViewPlaceholder = @"评论内容";
        vc.textViewValue =commentView.inputTF.text;
        vc.limitCount = 200;
        vc.callback = ^(NSString *content){
            [weakSelf sendCommentWith:content];
        };
    
        if (_play_switch == YES) {
            self.videoPause = YES;
        }
        vc.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
        [self.navigationController pushViewController:vc animated:YES];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
   
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    self.navigationController.navigationBar.hidden = NO;
}


#pragma mark -获取评论
- (void)requesetCommentData:(BOOL)isDownRefresh {
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"tblStudyDataId"] = _model.ID;
    params[@"pageSize"] =@(10);

    params[@"currentPage"] =@(self.page);
    defineWeakSelf;
    [[HELNetworkManager sharedMg] POST:kCoureCommmets_url parameters:params success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            NSMutableArray *arr = [NSMutableArray array];
            if ([responseObject[@"rows"] isKindOfClass:[NSArray class]]) {
                arr = [HELCourseCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]];
            }

            //判断是上拉刷新？  还是下拉加载？
            if (isDownRefresh) {
                if (weakSelf.page == [responseObject[@"pages"] integerValue] || arr.count == 0) {
                    weakSelf.cwq_tableView.footer.hidden = YES;
                }else {
                    weakSelf.cwq_tableView.footer.hidden = NO;
                }
                weakSelf.commentDataArray = arr;
                [weakSelf.cwq_tableView.header endRefreshing];
            }else {
                NSMutableArray *muArr = [weakSelf.commentDataArray mutableCopy];
                
                [muArr addObjectsFromArray:arr];
                weakSelf.commentDataArray = [muArr copy];
                if (weakSelf.page == [responseObject[@"pages"] integerValue]) {
                    weakSelf.cwq_tableView.footer.hidden = YES;
                }
                [weakSelf.cwq_tableView.footer endRefreshing];

            }
            if (weakSelf.commentDataArray.count<=0) {
                weakSelf.cwq_tableView.loading = NO;
            }
            
            [weakSelf.cwq_tableView reloadData];
            
        }
    } failure:^(NSString *err) {
        if (isDownRefresh) {
            //下拉
            [weakSelf.cwq_tableView.header endRefreshing];
            if (weakSelf.commentDataArray.count<=0) {
                
                self.cwq_tableView.footer.hidden = YES;
                
            }else {
                
                self.cwq_tableView.footer.hidden = NO;
            }
        }else {
            //上拉
            [weakSelf.cwq_tableView.footer endRefreshing];
             weakSelf.page -= 1;
        }
        cwqHudRequestError(err);
        if (weakSelf.commentDataArray.count<=0) {
            weakSelf.cwq_tableView.loading = NO;
        }
        
    }];
}


#pragma mark -发送评论
- (void)sendCommentWith:(NSString *)content{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud(self.view);
    params[@"tblStudyDataId"] = _model.ID;
    params[@"userId"]=HEL_USERID;
    params[@"content"]=content;
    
    weakSelf_define;
    
    [[HELNetworkManager sharedMg] POST:kCourseSendComment parameters:params success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            alertMessage(responseObject[@"exception"]);
        }
        if (responseObject[@"content"]) {
            
            [weakSelf requesetCommentData:YES];
        }
        
        [hud hideAnimated:YES];
    } failure:^(NSString *err) {
        [hud hideAnimated:YES];
    }];
}

#pragma mark - <UITableViewData and UITableDelegate>

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CWQVideoCommentSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
    return header;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"评论";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.commentDataArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HELCourseCommentModel *model = self.commentDataArray[indexPath.row];
    CGFloat height = [tableView fd_heightForCellWithIdentifier:cellID configuration:^(CWQVideoCommentCell *cell) {
     cell.model = model;

    }];
    return height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CWQVideoCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    HELCourseCommentModel *model = self.commentDataArray[indexPath.row];
    cell.model = model;
  
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    
}

#pragma mark - -------屏幕旋转--------------------
/*
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return toInterfaceOrientation != UIDeviceOrientationPortraitUpsideDown;
}

- (BOOL)shouldAutorotate
{
    //    if ([self.topViewController isKindOfClass:[AddMovieViewController class]]) { // 如果是这个 vc 则支持自动旋转
    return YES;
    //    }
    //    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{

    if (self.interfaceOrientation==UIDeviceOrientationLandscapeRight) {
        return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
    }else {
        return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskPortrait;
    }
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
//    if (interfaceOrientation == (UIInterfaceOrientationPortrait | UIInterfaceOrientationPortraitUpsideDown|
//        UIInterfaceOrientationLandscapeLeft|
//        UIInterfaceOrientationLandscapeRight)) {
////        [self cwqFullScreen:_playMenu.cwqFullScreen];
////        _screenPortrait = YES;
//    }else {
////        _screenPortrait = NO;
//    
//    }
    rotateToScreen = YES;
    [super clickScreenOrientation:_playMenu.cwqFullScreen];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

 */
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
